from io import BytesIO

from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse
from django.views import View
from django.views.decorators.http import require_GET
from django.core.cache import cache, caches

from apps.app_auth.form import LoginForm
from utils.captcha.xfzcaptcha import Captcha
from utils.resultful import ResultCode


class LoginView(View):
    def get(self, request):
        return render(request, 'cms/login.html')

    def post(self, request):
        form = LoginForm(request.POST)
        if form.is_valid():
            account = form.cleaned_data.get('account')
            password = form.cleaned_data.get('password')
            user = authenticate(username=account, password=password)
            if user:
                if user.is_active:
                    login(request, user)
                    request.session.set_expiry(0)
                    return ResultCode.ok(msg="登录成功~~")
                else:
                    return ResultCode.auth_error(msg="您的账号未激活或已被冻结~~")
            else:
                return ResultCode.params_error(msg="账号或密码错误~~")
        else:
            return ResultCode.params_error(msg=form.get_once_errors())


def logout_view(request):
    logout(request)
    return redirect(reverse("auth:login"))


@require_GET
def img_captcha(request):
    text, image = Captcha.gene_code()
    out = BytesIO()
    image.save(out, 'png')
    out.seek(0)
    response = HttpResponse(content_type='image/png')
    response.write(out.read())
    response['Content-length'] = out.tell()

    cache.set(f'img_captcha_{text.lower()}', text.lower(), 1 * 60)

    return response

#
# @require_GET
# def sms_captcha(request):
#     text, image = Captcha.gene_code()
#     out = BytesIO()
#     image.save(out, 'png')
#     out.seek(0)
#     response = HttpResponse(content_type='image/png')
#     response.write(out.read())
#     response['Content-length'] = out.tell()
#
#     cache.set(f'sms_captcha_{text.lower()}', text.lower(), 1 * 60)
#
#     return response
